package com.drojian.page5;

import android.graphics.Rect;
import android.view.View;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

public class SpacesItemDecoration extends RecyclerView.ItemDecoration {
    private int space;

    public SpacesItemDecoration(int space) {
        this.space = space; // 单位通常是dp，你需要将其转换为像素
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        // 设置item的四周外边距
        outRect.left = space;
        outRect.right = space;
        outRect.top = space;
        outRect.bottom = space;

        if (parent.getLayoutManager() instanceof GridLayoutManager) {
            GridLayoutManager gridLayoutManager = (GridLayoutManager) parent.getLayoutManager();
            int position = parent.getChildAdapterPosition(view);
            int spanCount = gridLayoutManager.getSpanCount();

            if (position >= 0 && position < spanCount) { // 第一行
                outRect.top = 0; // 第一个item的顶部不加间距
            }
            outRect.bottom = space; // 每个item底部都加间距
            outRect.right = space; // 每个item右边都加间距

            if (position % spanCount == spanCount - 1) { // 最后一列
                outRect.right = 0; // 右边最后一个item不加右边距
            }
        } else if (parent.getLayoutManager() instanceof LinearLayoutManager) {
            // 线性布局管理器的处理逻辑，如果需要的话
        }
    }
}